package com.yzl.frelink.service.analyze;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Service;

import com.yzl.frelink.entities.Fretish;
import com.yzl.frelink.entities.chart.Parameter;
import com.yzl.frelink.entities.component.Chart;

@Service
public class TypeAnalyzer {
    public void setParamsType(Chart chart, Fretish[] reqs) {
        for (Parameter param : chart.getParameters()) {
            param.initParameter(checkParamType(chart, param, reqs));
        }
    }

    public String checkParamType(Chart chart, Parameter param, Fretish[] reqs) {
        for (Fretish req : reqs) {
            String var = param.getName();
            String content = req.getContent();
            String typeInt = ".*\\b" + var + "\\s*:=\\s*\\d+\\b.*";
            String typeDouble = ".*\\b" + var + "\\s*:=\\s*\\d+\\.\\d+\\b.*";
            String typeUnset = ".*\\b" + var + "\\s*:=\\s*([a-zA-Z_0-9])+\\b.*";
            if (content.matches(typeInt)) {
                return "int8";
            } else if (content.matches(typeDouble)) {
                return "double";
            } else if (content.matches(typeUnset)) {
                Matcher m = Pattern.compile(typeUnset).matcher(content);
                if (m.find()) {
                    String assignedVar = m.group(1);
                    Parameter assignedParam = chart.getParameterByName(assignedVar);
                    if (assignedParam != null) {
                        return checkParamType(chart, assignedParam, reqs);
                    } else return "bool";
                } else return "bool";
            } else {
                return "bool";
            }
        }
        return "bool";
    }
}
